package com.finance.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.finance.entity.AsyncRequest;
import com.finance.mapper.AsyncRequestMapper;
import com.finance.service.AsyncRequestService;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class AsyncRequestServiceImpl extends ServiceImpl<AsyncRequestMapper, AsyncRequest> implements AsyncRequestService {
    
    @Override
    public void createAsyncRequest(String dataType, String searchDate, String cinemaId, String traceId) {
        AsyncRequest request = new AsyncRequest();
        request.setDataType(dataType);
        request.setSearchDate(searchDate);
        request.setCinemaId(cinemaId);
        request.setTraceId(traceId);
        request.setStatus(0); // 等待中
        request.setRetryCount(0);
        request.setCreatedAt(LocalDateTime.now());
        request.setUpdatedAt(LocalDateTime.now());
        save(request);
    }
    
    @Override
    public void updateStatus(Long id, Integer status, String errorMessage) {
        AsyncRequest request = getById(id);
        if (request != null) {
            request.setStatus(status);
            request.setErrorMessage(errorMessage);
            request.setUpdatedAt(LocalDateTime.now());
            updateById(request);
        }
    }
    
    @Override
    public List<AsyncRequest> getPendingRequests() {
        LambdaQueryWrapper<AsyncRequest> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(AsyncRequest::getStatus, 0) // 等待中
               .lt(AsyncRequest::getRetryCount, 3) // 重试次数小于3次
               .orderByAsc(AsyncRequest::getCreatedAt);
        return list(wrapper);
    }
    
    @Override
    public void incrementRetryCount(Long id) {
        AsyncRequest request = getById(id);
        if (request != null) {
            request.setRetryCount(request.getRetryCount() + 1);
            request.setUpdatedAt(LocalDateTime.now());
            updateById(request);
        }
    }
} 